#include "../Base/stdafx.h"
#include "Caller.h"

//-----------------------------------------------------------------
// Caller methods
//-----------------------------------------------------------------
bool Caller::AddActionListener(Callable* targetPtr)
{
	return AddListenerObject(targetPtr);
}	

bool Caller::RemoveActionListener(const Callable* targetPtr) 
{
	return RemoveListenerObject(targetPtr);
}

class CallAllActions
{
public:
	CallAllActions(Caller* callerPtr) : m_CallerPtr(callerPtr)
	{}

	void operator()(Callable* callablePtr)
	{
		callablePtr->CallAction(m_CallerPtr);
	}

private:
	Caller* m_CallerPtr;
};

bool Caller::CallListeners()   
{	
	/*
	for (vector<Callable*>::iterator it = m_TargetList.begin(); it != m_TargetList.end(); ++it)
	{
		(*it)->CallAction(this);	
	}
	*/
	for_each(m_TargetList.begin(), m_TargetList.end(), CallAllActions(this));

	return (m_TargetList.size() > 0);
}

bool Caller::AddListenerObject(Callable* targetPtr) 
{
	/*
	for (vector<Callable*>::iterator it = m_TargetList.begin(); it != m_TargetList.end(); ++it)
	{
		if ((*it) == target) return false;
	}*/
	vector<Callable*>::iterator pos = find(m_TargetList.begin(), m_TargetList.end(), targetPtr);

	if (pos != m_TargetList.end()) return false;
	
	m_TargetList.push_back(targetPtr);
	return true;
}
	
bool Caller::RemoveListenerObject(const Callable* targetPtr) 
{
	vector<Callable*>::iterator pos = find(m_TargetList.begin(), m_TargetList.end(), targetPtr); // find algorithm from STL

	if (pos == m_TargetList.end()) return false;

	m_TargetList.erase(pos);
	return true;
}
